import React, { useEffect, useState } from 'react';
import type { TableColumnsType } from 'antd';
import { Badge, Table } from 'antd';
import { downloadHistoryDocApi, getHistoryListApi } from '../../api';
import type { DownloadHistoryRecord, GetHistoryChildrenData, GetHistoryCompanyList, GroupHistoryData } from '../../types';
import dayjs from 'dayjs';

interface HistoryDataType{
  key:React.Key
  total:number
}

const expandColumns: TableColumnsType<GetHistoryCompanyList> = [
  { title: '年', dataIndex: 'year', key: 'year' },
  { title: '月', dataIndex: 'month', key: 'month' },
  { title: '日', dataIndex: 'day', key: 'day' },
  { title: '企业名称', dataIndex: 'name', key: 'name' },
  {
    title: '金额',
    key: 'amount',
    render: (_,values) => <Badge status="success" text={values.amount} />,
  },
  { title: '支行', dataIndex: 'bank_name', key: 'bank_name' },
  {
    title: '创建时间',dataIndex:'created_at',
    key: 'created_at',
  },
];

const columns: TableColumnsType<HistoryDataType> = [
  { title: '创建时间', dataIndex: 'create_at', key: 'create_at' },
  { title: '总共', dataIndex: 'total', key: 'total' },
  { title: '操作', key: 'operation', render: (record:DownloadHistoryRecord) => <a onClick={()=> downloadFn(record)}>下载</a> },
];

const downloadFn = async (record:DownloadHistoryRecord) =>{
  console.log(record.create_at.split('-'))
  const [year,month,day] = record.key.split('-')
  if(year){
    try{
      const res = await downloadHistoryDocApi(year,month,day)
      if (res.status === 200) {
        // 从响应头获取文件名，如果没有则使用默认文件名
        const contentDisposition = res.headers['content-disposition'];
        let fileName = `付款凭证_${year}年${month}月${day}日.docx`;
        
        if (contentDisposition) {
            const fileNameMatch = contentDisposition.match(/filename\*?=["']?(?:UTF-\d["']*)?([^;"']*)["']?;?/i);
            if (fileNameMatch && fileNameMatch[1]) {
                fileName = decodeURIComponent(fileNameMatch[1]);
            }
        }

        // 创建 Blob 对象
        const blob = new Blob([res.data], {
            type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        });

        // 创建下载链接
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = fileName;
        document.body.appendChild(link);
        link.click();
        
        // 清理
        window.URL.revokeObjectURL(url);
        document.body.removeChild(link);
        
        return { success: true, fileName };
    } else {
        throw new Error('生成文档失败');
    }
    }catch(error:unknown){
      console.error('生成文档错误:', error);
        // 如果是Blob类型的错误，尝试解析错误信息
        if (error.response && error.response.data instanceof Blob) {
          try {
            const errorText = await error.response.data.text();
            const errorData = JSON.parse(errorText);
            return { 
              success: false, 
              message: errorData.message || '生成文档失败',
              error: errorData.error
            };
          } catch (parseError: unknown) {
            return { 
              success: false, 
              message: '生成文档失败',
              error: '无法解析错误信息'
            };
          }
        }
        // return { 
        //   success: false, 
        //   message: error.response?.data?.message || '生成文档失败',
        //   error: error.message
        // };
      }
  }
}

const HistoryList: React.FC = () => {
  // 分组数据-上层数据
  const [upData,setUpData] = useState<HistoryDataType[]>()
  const getHistoryCompanyListFn = async () => {
    const res = await getHistoryListApi();
    const groupedByData: GroupHistoryData = {};
    let dateKey
    if (Array.isArray(res.data.data)) {
      res.data.data.forEach((item) => {
        dateKey = `${item.year}-${String(item.month).padStart(2, '0')}-${String(item.day).padStart(2, '0')}`;
        if (!groupedByData[dateKey]) {
          groupedByData[dateKey] = [];
        }
        groupedByData[dateKey].push(item);
      });
    }
    const dataSource = Object.entries(groupedByData).map<HistoryDataType>(([dateKey, items]) => ({
      key: dateKey,
      create_at: dateKey,
      total: items.length,
      // 这里的info取值的属性名不能是chilren，否则会导致外层嵌套的数据重复空白行
      info: items.map(item=>({
        ...item,
        key:item.id,
        created_at:dayjs(item.created_at).format('YYYY-MM-DD HH:mm')
      }))
    }));
    // console.log('dataSource',dataSource)
    setUpData(dataSource); // 更新用于外层表格的数据源
  };
  // type-> GetHistoryChildrenData
  const expandedRowRender = (record:HistoryDataType):React.ReactNode => {
    const childData = record as unknown as GetHistoryChildrenData;
    return (
    <Table
      columns={expandColumns}
      dataSource={childData.info}
      pagination={false}
    />
  );}
  useEffect(()=>{
    getHistoryCompanyListFn()
  },[])

  return(
    <>
      <Table<HistoryDataType>
        columns={columns}
        expandable={{ 
          expandedRowRender,
          defaultExpandedRowKeys: ['0'],
        }}
        dataSource={upData}
        size="small"
      />
  </>
  )
}

export default HistoryList;